import 'dart:io';
import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:zootix/models/zt_im_message.model.dart';
import 'package:zootix/screens/chat/zt_micphone.dart';
import 'package:zootix/screens/chat/zt_private_message_item.dart';
import 'package:zootix/services/zt_translate.service.dart';
import 'package:zootix/store/zt_auth.store.dart';
import 'package:zootix/util/zt_screen_adaper_util.dart';
import 'package:zootix/widgets/zt_empty.dart';
import 'package:zootix/zt_app_theme.dart';
import 'zt_private_chat.controller.dart';

class ZtPrivateChatPage extends StatelessWidget {
  final _controller =
      Get.put<ZtPrivateChatController>(ZtPrivateChatController());

  ZtPrivateChatPage({super.key}) {
    _controller.isCustomerService =
        Get.arguments?['isCustomerService'] ?? false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF7F8FA),
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Row(children: [
          Expanded(
              child: Text(
            Get.arguments?['nickname'] ?? '',
            overflow: TextOverflow.ellipsis,
            softWrap: false,
            style: TextStyle(
                fontWeight: FontWeight.w500, fontSize: ZtScreenAdaper.sp(16)),
          )),
        ]),
        actions: [
          if (!_controller.isCustomerService)
            InkWell(
                onTap: () {
                  _controller.openMore();
                },
                child: Image(
                    height: ZtScreenAdaper.width(25),
                    width: ZtScreenAdaper.width(25),
                    image: const AssetImage(
                        'assets/images/private_chat_more.png'))),
          SizedBox(
            width: ZtScreenAdaper.width(10),
          )
        ],
      ),
      body: _buildChatMessages(),
    );
  }

  Widget _buildChatMessages() {
    return Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Obx(() => Expanded(
              child: GestureDetector(
                  onTap: () {
                    Get.focusScope?.unfocus();
                    _controller.onCancelBtnPress();
                    _controller.voiceShowing.value = false;
                    _controller.emojiShowing.value = false;
                    _controller.filePickerShowing.value = false;
                  },
                  child: SmartRefresher(
                      enablePullDown: false,
                      enablePullUp: true,
                      controller: _controller.refreshController,
                      onLoading: () {
                        _controller.onRefresh();
                      },
                      child: _controller.chatMessages.isEmpty &&
                              [
                                RefreshStatus.idle,
                                RefreshStatus.completed
                              ].contains(
                                  _controller.refreshController.headerStatus)
                          ? ZtEmpty(text: "No Messages.")
                          : Align(
                              // 关键代码 alignment: Alignment.topCenter,
                              alignment: Alignment.topCenter,
                              child: ListView.builder(
                                  shrinkWrap: true,
                                  reverse: true,
                                  controller: _controller.scrollController,
                                  itemCount: _controller.chatMessages.length,
                                  itemBuilder: (_, index) =>
                                      ZtPrivateMessageItem(
                                          chatModel:
                                              _controller.chatMessages[index],
                                          index: index))))))),
          _buildSearchBar(),
        ]);
  }

  Widget _buildSearchBar() {
    return Listener(
        onPointerMove: _controller.onPointMove,
        onPointerUp: _controller.onPointUp,
        child: Align(
          alignment: Alignment.bottomCenter,
          child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.3),
                    spreadRadius: 2,
                    blurRadius: 5,
                    offset: const Offset(0, -1), // 控制阴影的位置偏移
                  ),
                ],
              ),
              child: Obx(
                () => _controller.voiceShowing.value
                    ? _buildVoicePopup()
                    : _controller.filePickerShowing.value
                        ? _buildFilePickerPopup()
                        : Column(
                            children: [
                              Container(
                                  padding: EdgeInsets.symmetric(
                                      horizontal: ZtScreenAdaper.width(20),
                                      vertical: ZtScreenAdaper.height(15)),
                                  child: Row(
                                    children: [
                                      SizedBox(
                                        width: ZtScreenAdaper.width(10),
                                      ),
                                      _buildVoiceBtn(),
                                      SizedBox(
                                        width: ZtScreenAdaper.width(20),
                                      ),
                                      Expanded(
                                          child: Stack(
                                        alignment: Alignment.center,
                                        children: [
                                          _buildSearchInput(),
                                          Positioned(
                                              width: ZtScreenAdaper.width(30),
                                              height: ZtScreenAdaper.width(30),
                                              right: 0,
                                              child: _buildEmojiBtn())
                                        ],
                                      )),
                                      SizedBox(
                                        width: ZtScreenAdaper.width(20),
                                      ),
                                      _buildFilePickerBtn(),
                                    ],
                                  )),
                              SizedBox(
                                height: ZtScreenAdaper.height(5),
                              ),
                              _buildEmojiPicker(),
                            ],
                          ),
              )),
        ));
  }

  Widget _buildVoiceBtn() {
    return InkWell(
      onTap: () {
        _controller.voiceShowing.value = !_controller.voiceShowing.value;
      },
      child: Image(
          height: ZtScreenAdaper.width(30),
          width: ZtScreenAdaper.width(30),
          image: const AssetImage('assets/images/private_chat_voice.png')),
    );
  }

  Widget _buildVoicePopup() {
    return Container(
        padding: EdgeInsets.symmetric(horizontal: ZtScreenAdaper.width(30)),
        height: ZtScreenAdaper.height(300),
        child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [_buildCancelBtn(), BuildMic(), _buildVoiceSubmitBtn()]));
  }

  Widget _buildCancelBtn() {
    return InkWell(
      onTap: _controller.onCancelBtnPress,
      child: Container(
        key: _controller.containerCancelKey,
        padding: EdgeInsets.all(
            ZtScreenAdaper.width(_controller.isHoverOnCancel.value ? 20 : 10)),
        decoration: BoxDecoration(
            color: Colors.grey[200], borderRadius: BorderRadius.circular(50)),
        child: Icon(
          Icons.close,
          color: Colors.grey[400],
          size: ZtScreenAdaper.sp(35),
        ),
      ),
    );
  }

  Widget _buildSearchInput() {
    return ConstrainedBox(
      constraints: BoxConstraints(maxHeight: ZtScreenAdaper.height(40)),
      child: GetBuilder<ZtPrivateChatController>(
        id: 'Typing something)',
        builder: (_) => TextField(
            onSubmitted: (_) {
              _controller.sendMessage();
            },
            onTap: () {
              _controller.emojiShowing.value = false;
              if (_controller.textEditingController.text.isNotEmpty) {
                _controller.cursorPosition =
                    _controller.textEditingController.selection.baseOffset;
              } else {
                _controller.cursorPosition = null;
              }
            },
            textInputAction: TextInputAction.send,
            controller: _controller.textEditingController,
            decoration: InputDecoration(
              contentPadding: EdgeInsets.only(
                  left: ZtScreenAdaper.width(10),
                  right: ZtScreenAdaper.width(35)),
              border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(15),
                  borderSide: BorderSide.none),
              filled: true,
            )),
      ),
    );
  }

  Widget _buildEmojiBtn() {
    return Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(40),
        ),
        child: InkWell(
          onTap: () async {
            Get.focusScope?.unfocus();
            _controller.emojiShowing.value = !_controller.emojiShowing.value;
          },
          child: Image(
              height: ZtScreenAdaper.height(30),
              width: ZtScreenAdaper.width(30),
              image: const AssetImage('assets/images/private_chat_emoji.png')),
        ));
  }

  Widget _buildEmojiPicker() {
    return Obx(() => Offstage(
          offstage: !_controller.emojiShowing.value,
          child: SizedBox(
            height: ZtScreenAdaper.height(250),
            child: EmojiPicker(
                onEmojiSelected: (Category? category, Emoji emoji) {
                  _controller.onEmojiSelected(emoji);
                },
                onBackspacePressed: _controller.onBackspacePressed,
                config: Config(
                    columns: 7,
                    emojiSizeMax: 32 * (Platform.isIOS ? 1.30 : 1.0),
                    verticalSpacing: 0,
                    horizontalSpacing: 0,
                    initCategory: Category.RECENT,
                    // bgColor: const Color(0xFFF2F2F2),
                    indicatorColor: ZtAppTheme.primaryColor,
                    iconColor: Colors.grey,
                    iconColorSelected: ZtAppTheme.primaryColor,
                    backspaceColor: ZtAppTheme.primaryColor,
                    skinToneDialogBgColor: Colors.white,
                    skinToneIndicatorColor: Colors.grey,
                    enableSkinTones: true,
                    recentTabBehavior: RecentTabBehavior.RECENT,
                    // showRecentsTab: true,
                    recentsLimit: 28,
                    noRecents: const Text(
                      'No Recents',
                      style: TextStyle(fontSize: 20, color: Colors.black26),
                      textAlign: TextAlign.center,
                    ), //
                    tabIndicatorAnimDuration: kTabScrollDuration,
                    categoryIcons: const CategoryIcons(),
                    buttonMode: ButtonMode.CUPERTINO)),
          ),
        ));
  }

  Widget _buildVoiceSubmitBtn() {
    return InkWell(
      onTap: () {
        _controller.sendMediaMessage(RCIMIWMessageType.voice);
      },
      child: Container(
          key: _controller.containerSendKey,
          padding: EdgeInsets.all(
              ZtScreenAdaper.width(_controller.isHoverOnSend.value ? 20 : 10)),
          decoration: BoxDecoration(
              color: ZtAppTheme.primaryColor,
              borderRadius: BorderRadius.circular(50)),
          child: Icon(
            Icons.check,
            color: Colors.white,
            size: ZtScreenAdaper.sp(35),
          )),
    );
  }

  Widget _buildFilePickerBtn() {
    return InkWell(
      onTap: () {
        _controller.filePickerShowing.value =
            !_controller.filePickerShowing.value;
      },
      child: Image(
          height: ZtScreenAdaper.width(37),
          width: ZtScreenAdaper.width(37),
          image:
              const AssetImage('assets/images/private_chat_upload_file.png')),
    );
  }

  Widget _buildFilePickerPopup() {
    return Container(
        decoration: const BoxDecoration(color: Color(0xFFF7F8FA)),
        padding: EdgeInsets.symmetric(horizontal: ZtScreenAdaper.width(30)),
        height: ZtScreenAdaper.height(200),
        child: Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
          InkWell(
            onTap: _controller.pickPhoto,
            child:
                Column(mainAxisAlignment: MainAxisAlignment.center, children: [
              Image(
                  width: ZtScreenAdaper.width(50),
                  image:
                      const AssetImage('assets/images/image_picker_icn.png')),
              const Text('Photo')
            ]),
          ),
          SizedBox(
            width: ZtScreenAdaper.width(30),
          ),
          InkWell(
              onTap: _controller.pickFile,
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image(
                        width: ZtScreenAdaper.width(50),
                        image: const AssetImage(
                            'assets/images/file_picker_icon.png')),
                    const Text('File')
                  ])),
        ]));
  }
}
